import matplotlib.pyplot as plt
import numpy as np

# 定义类别和两组数据
categories = ["Category A", "Category B", "Category C", "Category D"]
values1 = [25, 30, 15, 5]
values2 = [10, 15, 20, 25]
values3 = [15, 20, 30, 10]

# 计算每个类别的总值
total_values = values1 + values2 + values3

# 计算每个数据集的累计值，用于堆叠
cumulative_values = np.zeros(len(categories))
cumulative_values[0] = values1[0]
for i in range(1, len(categories)):
    cumulative_values[i] = cumulative_values[i - 1] + values1[i]

# 绘制堆叠条形图
bottom = np.zeros(len(categories))  # 初始底部值为0
plt.bar(categories, values1, width=0.5, label="Dataset 1", bottom=bottom)
bottom += values1  # 更新底部值
plt.bar(categories, values2, width=0.5, label="Dataset 2", bottom=bottom)
bottom += values2  # 更新底部值
plt.bar(categories, values3, width=0.5, label="Dataset 3", bottom=bottom)

# 添加图例
plt.legend()

# 添加标题和轴标签
plt.title("Stacked Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")

# 显示图形
plt.tight_layout()  # 调整布局以适应图例
plt.show()
